﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.Public
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class HYAddTitleBlocks : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				UIApplication application = commandData.Application;
				UIDocument activeUIDocument = application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
                Autodesk.Revit.DB.View activeView = document.ActiveView;
                if ((int)activeView.ViewType != 6)
				{
					YJKMessageBox.Show("请切换到图纸视图下运行此命令！");
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					transaction = new Transaction(document, "插入图框");
					transaction.Start();
					AddTitleBlocksForm addTitleBlocksForm = new AddTitleBlocksForm(document);
					addTitleBlocksForm.ShowDialog();
					if (addTitleBlocksForm.DialogResult == DialogResult.OK)
					{
						FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document, activeView.Id);
						List<Element> list = filteredElementCollector.OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_TitleBlocks).ToElements().ToList<Element>();
						if (list.Count > 0)
						{
							DialogResult dialogResult = YJKMessageBox.Show("是否覆盖当前图框？", MessageBoxButtons.YesNo);
							if (dialogResult == DialogResult.No)
							{
								return Autodesk.Revit.UI.Result.Succeeded;
							}
							foreach (Element element in list)
							{
								FamilyInstance familyInstance = element as FamilyInstance;
								familyInstance.Symbol = addTitleBlocksForm.fs;
							}
							document.Regenerate();
						}
						else
						{
							XYZ xyz = new XYZ(0.0, 0.0, 0.0);
							UnifiedModified.ActivateFamilySymbol(addTitleBlocksForm.fs);
							document.Create.NewFamilyInstance(xyz, addTitleBlocksForm.fs, document.ActiveView);
						}
					}
					transaction.Commit();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
                    if ((int)status == 1)
					{
						transaction.Commit();
					}
                    else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
